import kriging from "./kriging.js"

/**
 * 通过克里金插值算法绘制热力图
 * @param {object} posValues 形式如[[x, y, v], [], ...]  x在0-width范围之内，y在0-height范围之内，v必须大于0
 * @param {number} width 宽度
 * @param {number} height 高度
 * @param {object} krigingOptions
 * @returns {number[] | undefined} 返回结果，如果为undefined，说明计算出错！
 * @static
 * @memberof Obj.HeatMap
 * @example
 * var gridData = new Array(100*100);
 * gridData.fill(0);
 * const posValues = [[10, 10, 100], [10, 90, 500], [90, 10, 300], [90, 90, 1000]];
 * var gridData = XE.Obj.HeatMap.getGridDataFromKriging(posValues, 100, 100, gridData);
 */

function getGridDataFromKriging(posValues, width, height, resultGridData) {
  var _ref = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {},
    _ref$model = _ref.model,
    model = _ref$model === undefined ? "exponential" : _ref$model,
    _ref$sigma = _ref.sigma2,
    sigma2 = _ref$sigma === undefined ? 0 : _ref$sigma,
    _ref$alpha = _ref.alpha,
    alpha = _ref$alpha === undefined ? 100 : _ref$alpha;

  var gridData = resultGridData;

  try {
    // TODO(vtxf): posValues 需要去重，否则克里金插值可能报错
    var values = [];
    var xs = [];
    var ys = [];
    posValues.forEach(function(e) {
      xs.push(e[0]);
      ys.push(e[1]);
      values.push(e[2]);
    });

    var variogram = kriging.train(values, xs, ys, model, sigma2, alpha);

    for (var i = 0; i < width; ++i) {
      for (var j = 0; j < height; ++j) {
        gridData[j * width + i] = kriging.predict(i, j, variogram);
        if (!isFinite(gridData[j * width + i])) {
          throw new Error('克里金插值计算出错！');
        }
      }
    }

    return gridData;
  } catch (error) {
    console.warn('error: ' + error);
    return undefined;
  }
}

export default getGridDataFromKriging;
